package com.zhanghe.im.handler;

import com.zhanghe.im.request.QuitGroupRequestPacket;
import com.zhanghe.im.response.QuitGroupResponsePacket;
import com.zhanghe.im.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

public class SimpleQuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket msg) throws Exception {
       String groupId = msg.getGroupId();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
        if(channelGroup!=null){
            String userName = SessionUtil.getSession(ctx.channel()).getUserName();
            System.out.println("用户["+userName+"] 退出群:"+groupId);
            channelGroup.remove(ctx.channel());
            quitGroupResponsePacket.setGroupId(groupId);
            quitGroupResponsePacket.setSuccess(true);
        }else{
            quitGroupResponsePacket.setSuccess(false);
        }
        ctx.channel().writeAndFlush(quitGroupResponsePacket);
    }
}
